#!/usr/bin python3
# -*- coding:UTF-8 -*-
# Author: nigo
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
import pandas as pd
import os
import re

def decode_str(msg):
    """解码文本"""
    value, charset = decode_header(msg)[0]
    if charset:
        value = value.decode(charset)
    return value

def decode_address(msg):
    """解析出邮件地址"""
    address,charset = parseaddr(msg)
    return charset

def extract_info(path):
    """提取邮件信息"""
    with open(path,encoding='utf8') as f:
        data = f.read() # 读取eml文件
        email = Parser().parsestr(data)
        ip = email['X-Originating-IP'] # ip地址
        ip = re.sub("\[|\]",'',ip)
        source = email.get('From') # 发件人
        source = decode_address(source) # 发件人邮箱地址
        to = email['to'] # 收件人
        to = decode_address(to) # 收件人邮箱地址
        subject = email['subject'] # 邮件标题
        subject = decode_str(subject) # 邮件标题解码为明文
        series = pd.Series([subject,source,to,ip]) # 创建一行pandas的series
        return series

def GetFileList(dir, fileList):
    """获取文件列表"""
    newDir = dir
    if os.path.isfile(dir):
        fileList.append(dir)
    elif os.path.isdir(dir):  
        for s in os.listdir(dir):
            newDir=os.path.join(dir,s)
            GetFileList(newDir, fileList)  
    return fileList

if __name__ == "__main__":
    path = 'file' 
    file_list = GetFileList(path,[])# 获取'file'目录下所有文件路径列表
    df = pd.DataFrame()
    for path in file_list:
        s = extract_info(path)  
        df = df.append(s,ignore_index=True)
    df.columns = ['标题','发件人','收件人','ip']
    df.to_excel('邮件信息.xlsx',index=False)
